import axios, { AxiosError } from "axios";
import NProgress from "nprogress";
import showTip from "@/plugins/notice";

const ERROR_MSG = {
    ECONNABORTED: "请求超时,请稍后重试",
    ETIMEDOUT: "网络异常,请检查网络连接",
    ERR_NETWORK: "网络异常,请检查网络连接"
}
const HTTP_MSG = {
    401: "未授权",
    403: "未授权",
    404: "您所访问的资源不存在",
    500: "服务器异常,请联系管理员",
    DEFAULT: "服务器忙,请稍后重试"
}

const requestSuccess = function(config){
    NProgress.start();
    return config;
}

const responseSuccess =  function (response) {
    NProgress.done();
    // 统一成功处理
    // showTip("请求成功","","success")
    return response.data;
}

const responseError = function (error) {
    NProgress.done();
    // console.log(111)
    let title = "运行错误,请联系管理员";
    // if (error instanceof axios.AxiosError) {
    if (error instanceof AxiosError) {
        let { status, code } = error.toJSON();
        if (status) {
            title = HTTP_MSG[status] || HTTP_MSG.DEFAULT;
        } else {
            title = ERROR_MSG[code];
        }
    }
    // alert(title)
    showTip("请求失败",title,"error")
    return Promise.reject(error);
}

const createRequest = function(baseURL=""){
    // 基于axios的所有功能生成一个 副本对象
    let tempAxios = axios.create({
        baseURL
    });
    // 请求拦截器注册
    tempAxios.interceptors.request.use(requestSuccess);
    // 响应拦截器注册
    tempAxios.interceptors.response.use(responseSuccess,responseError);

    return tempAxios
}

export default createRequest;
